import { buildThemeAPI, getMetadataAPI } from "@/api/build";
import { BuilderResult } from "@/common/builder-result";
import { ExportedItem } from "@/common/exported-item";
import { MetaItem, MetaValueChange, ThemeMetaItem } from "@/common/meta-item";
import { MetaItemThemeType, Metadata } from "@/common/metadata";
import { Theme, ThemeConfig } from "@/common/theme";
import { useExtendCSSStore,useBuildCSSStore, useThemeMetadataStore,useThemeChangeStore } from "@/store/index";

export function themeMetadataUtils() {
  // 获取公共数据
  let extendCSS = useExtendCSSStore();
  // 保存编译后的样式
  let buildCSS=useBuildCSSStore();
  // 获取主题变量
  let themeMetadata = useThemeMetadataStore();
  // 获取主题变更信息
  let themeChange=useThemeChangeStore();
  /**
   * 重置变量
   */
  const clearModifiedDataCache=(): void =>{
    themeMetadata.updateModified([]);
    themeMetadata.updateIsRapid(false);
  }
  /**
   * 组装主题信息
   * @param themeName
   * @returns
   */
  function conformThemeName(themeName: string): Theme {
    let newThemeInfo = { name: "", colorScheme: "" };
    switch (themeName) {
      case "framework":
        newThemeInfo.name = themeName;
        newThemeInfo.colorScheme = themeChange.themeColor;
        break;
      default:
        newThemeInfo = themeChange.currentTheme;
    }
    return newThemeInfo;
  }

  /**
   * 获取变量集合
   */
  function getVariableCollection(themeInfo: Theme) {
    let variableRapidCollection: ExportedItem[] = [];
    if (
      themeMetadata.modifiedCollection.length > 0 &&
      themeMetadata.modifiedIsRapid
    ) {
      //当有基础变量的变更时候，追加一个变量的修改
      variableRapidCollection.push({
        key: "$variable-type",
        value: "rapidSettings"
      });
    }
    // 默认手写CSS是针对farris主题扩展，如果当前主题不是farris，则不追加这个变量
    if (themeInfo && themeInfo.name == "farris") {
      variableRapidCollection.push({
        key: "$extend-css",
        value: extendCSS.css
      });
    }
    return variableRapidCollection.concat(...themeMetadata.modifiedCollection);
  }
  /**
   * 如果已有元数据就按照当前的元数据取，
   * 如果没有元数据，就调用接口获取
   */
  function getMetadata(): Promise<Metadata> {
    if (themeMetadata.metadata) {
      return Promise.resolve(themeMetadata.metadata);
    }

    return getMetadataAPI().then((metadata: Metadata) => {
      if (!themeMetadata.metadata) {
        themeMetadata.updateMetadata(metadata);
      }
      return metadata;
    });
  }
  /**
   * 返回对应主题对下的变量定义
   */
  function getData(): Promise<MetaItem[]> {
    return getMetadata().then((metadata) => {
      //待替换 --------------------------ToDo 不这样写不通过
      let themeDetail = metadata[themeChange.currentTheme.name as keyof Metadata];
      if (typeof themeDetail == "object") {
        return themeDetail as MetaItem[];
      }
      return [];
      //return metadata['generic'];
    });
  }
  /**
   *  查找
   * @param key
   * @returns
   */
  function getDataItemByKey(key: string): Promise<MetaItem | undefined> {
    return getData().then((data: Array<MetaItem>) => {
      return data.find((item) => item.Key === key);
    });
  }
  /**
   * 生成主题
   *
   * 快速配置中：
   * 1、farris和framework共用变量
   * ---------------------------------------ToDo Ximena AxiosResponse
   */
  const buildTheme = (themeName = ""): Promise<BuilderResult> => {
    //比如{colorScheme: "light", name: "generic"}
    const currentTheme = conformThemeName(themeName);
    // 获取当前主题的信息
    //
    const buildResult = buildThemeAPI({
      makeSwatch: false,
      items: getVariableCollection(currentTheme),
      widgets: [],
      noClean: true,
      baseTheme:
        currentTheme.name + "." + currentTheme.colorScheme.replace(/-/g, ".")
    });
    console.log("编译主题之前");
    console.log(currentTheme);
    // const savedBuildNumber = ++this.globalBuildNumber;

    return buildResult.then((result) => {
      /**
       * result的结构
       *  {
       *  compiledMetadata: {'$base-accent':对象}
       *  css:"生成的css代码",
       *  swatchSelector:null,
       *  unusedWidgets:[],未使用的组件
       *  version:"21.2.3",
       *  widgets:["box","responsivebox"..]包含的组件
       * }
       *
       */
      // if (!this.forceRebuild && savedBuildNumber !== this.globalBuildNumber)
      // return;

      //   if(isFirstBootstrapBuild) {
      //       for(const dataKey in result.compiledMetadata) {
      //           if(Object.prototype.hasOwnProperty.call(result.compiledMetadata, dataKey)) {
      //               this.modifiedCollection.push({ key: dataKey, value: result.compiledMetadata[dataKey] });
      //           }
      //       }
      //   }

      let itemPromises: any[] = [];
      // 处理变量的值，此处返回的变量对应的是个 [object object]
      Object.keys(result.compiledMetadata).forEach((dataKey) => {
        if (
          Object.prototype.hasOwnProperty.call(result.compiledMetadata, dataKey)
        ) {
          itemPromises.push(getDataItemByKey(dataKey));
        }
      });
      // itemPromises 存储的都是异步对象，等待结果然后赋值
      return Promise.all(itemPromises).then((resolveItems) => {
        /**resolveItems 开始结构
         * {
         *   Key:"$base-accent",
         *   Name:"10. Accent color",
         *   Type:"color"
         * }
         * ....
         */
        resolveItems.forEach((item) => {
          if (item) {
            item.Value = result.compiledMetadata[item.Key];
          }
        });
        /**
         * resolveItems 结束之后结构
         * {
         *   Key:"$base-accent",
         *   Name:"10. Accent color",
         *   Type:"color",
         *   Value:"[object object]"
         * }
         * ....
         */
        // 记录当前的元数据
        if (themeMetadata.modifiedCollection.length == 0) {
          //待替换
          //避免对象的修改影响原值，此处用克隆的方式
          let metadataStr = JSON.stringify(
            themeMetadata.metadata[currentTheme.name]
          );
          themeMetadata.updateOriginalMetadata(JSON.parse(metadataStr));
        }
        // 记录当前主题的css
        buildCSS.updateCSS(
          `//${currentTheme.name} ${currentTheme.colorScheme}  \n` + result.css,currentTheme.name
        );

        return result;
      });
    });
  };

  /**
   * 多个主题同时被生成
   * framework框架主题和farris主题（默认主题）
   */
  const buildAll=(): Promise<Array<BuilderResult>>=> {
    let allThemeBuilded: any[] = [];
    // this.forceRebuild = true;
    ["framework", ""].forEach((item) => {
      allThemeBuilded.push(buildTheme(item));
    });
    return new Promise((resolve, reject) => {
      Promise.all(allThemeBuilded)
        .then((resArray) => {
          //this.forceRebuild = false;
          resolve(resArray);
        })
        .catch((rejArray) => {
          // this.forceRebuild = false;
          reject(rejArray);
        });
    });
  }

  /**
   * 重置所有变量
   */
  const resetVariables= (): void=> {
    clearModifiedDataCache();
    let metadataStr = JSON.stringify(themeMetadata.originalMetadata);
    // 更新全局数据
    themeMetadata.updateMetadataByThemeName(JSON.parse(metadataStr));
    // 重置自定义的样式
    buildCSS.updateCSS("","farris");
    buildCSS.updateCSS("","framework");
  }

  /**
   * 更新变量值
   * @param e
   * @param key
   * {changeValue:e,controlKey:key,variableType:this.variableType}
   */
  const updateSingleVariable = (metaChangeObj: MetaValueChange): void => {
    getDataItemByKey(metaChangeObj["controlKey"]).then((dataItem) => {
      if (!dataItem) {
        return;
      }
      if (dataItem.Value == undefined) {
        return;
      }
      if (dataItem.Value === metaChangeObj["changeValue"]) {
        return;
      }
      // #333 和#333333是否相等的排除
      if (dataItem.Type == "color") {
        let tColor = dataItem.Value.replace("#", "");
        if (dataItem.Value + tColor == metaChangeObj["changeValue"]) {
          return;
        }
      }
      dataItem.Value = metaChangeObj["changeValue"];
      if (metaChangeObj["variableType"] == "rapidSettings") {
        themeMetadata.updateIsRapid(true);
      }
      let tModifyCollection = [...themeMetadata.modifiedCollection];
      tModifyCollection = tModifyCollection.filter(
        (item) => item.key !== dataItem.Key
      );
      tModifyCollection.push({
        key: dataItem.Key,
        value: dataItem.Value
      });
      themeMetadata.updateModified(tModifyCollection);
      // 重新生成
      // this.build();
    });
  };

  /**
   * 获取基础变量的定义
   * themeNames是：多个主题的字符串：farris,framework
   * 返回的结果：
   * {farris:MetaItem[],framework:MetaItem[]}
   */
  const getBaseParameters = (themeNames: string): Promise<ThemeMetaItem> => {
    return getMetadata().then((metadata: Metadata) => {
      /**
       * items的结构
       * {
       *   Key:"$base-accent",
       *   Name:"10. Accent color",
       *   Type:"color",
       *   Value:"[object object]"
       * }
       * ....
       */
      let themeNamesArray = themeNames
        ? themeNames.split(",")
        : [ themeChange.currentTheme.name];
      let result: any = {};
      themeNamesArray.forEach((themeName) => {
        if (themeName) {
          result[themeName] = [];
          if (metadata.hasOwnProperty(themeName)) {
            (metadata[themeName as keyof MetaItemThemeType] || []).forEach(
              (item: MetaItem) => {
                const index = themeMetadata.metadata.baseParameters[
                  themeName
                ].indexOf(item.Key.replace("$", "@"));
                if (index >= 0) result[themeName][index] = item;
              }
            );
          }
        }
      });
      /**
       * 基础参数或者说是基础变量
       * baseParameters中项["@base-accent","@base-text-color","@base-bg","@base-border-color","@base-border-radius"]
       * 给这些基础变量赋值，值的来源来自于主题的变量定义
       *
       */
      return result;
    });
  };

  /**
   * 获取所有主题的颜色列表
   * 返回结果是[{"themeId":1,"name":"generic","colorScheme":"light","text":"Light","group":"Generic"},{}]
   */
  function getThemes(): Promise<ThemeConfig[]> {
    if (themeMetadata.metadata) {
      return Promise.resolve(themeMetadata.metadata.themes);
    }

    return getMetadata().then((metadata) => {
      if (!themeMetadata.metadata) {
        themeMetadata.updateMetadata(metadata);
      }
      return metadata.themes;
    });
  }

  const exportCSS = (themeName = ""): Promise<string> => {
    return new Promise((resolve, reject): void => {
      const currentTheme = conformThemeName(themeName);
      // 按照配置信息重新生成一遍主题，并把css内容返回
      let baseTheme = `${currentTheme.name}.${currentTheme.colorScheme.replace(/-/g, '.')}`;
      buildThemeAPI({
          makeSwatch: false,
          // outputColorScheme: outColorScheme,
          items: getVariableCollection(currentTheme),
          widgets: [],
          noClean: false,
          baseTheme:baseTheme
          // assetsBasePath,
          // removeExternalResources
        })
        .then(
          (result) => {
            resolve(result.css);
          },
          (error) => {
            reject(error);
          }
        );
    });
  }
  return {
    updateSingleVariable,
    getBaseParameters,
    buildTheme,
    exportCSS,
    resetVariables,
    buildAll,
    clearModifiedDataCache
  };
}
